import os
import cv2
from PIL import Image


def convert(item, img_width, img_height):
    location = item.split(' ')
    x1, y1, x2, y2 = int(location[-1].split(',')[0]), int(location[-1].split(',')[1]), int(
        location[-1].split(',')[2]), int(location[-1].split(',')[3])
    # print(location)
    # print(x1, y1, x2, y2)
    center_x = x1 + (x2 - x1) / 2
    center_y = y1 + (y2 - y1) / 2
    width = x2 - x1
    height = y2 - y1
    return str(center_x / img_width), str(center_y / img_height), str(width / img_width), str(height / img_height)


labels_path = r'G:\Utorrent_2.04_睿思推荐使用\DownloadingTorrents\yolov5\coco128\labels\train2017'
images_path = r'G:\Utorrent_2.04_睿思推荐使用\DownloadingTorrents\yolov5\coco128\images\train2017'
labels = os.listdir(labels_path)
for label in labels:
    # 获取图片的宽和高
    img = os.path.join(images_path, label.split('.txt')[0]) + '.png'
    image = Image.open(img)
    img_width, img_height = image.size[0], image.size[1]
    # 读入bbx
    with open(os.path.join(labels_path, label), 'r') as f:
        data = f.readlines()
    f.close()
    # 转换坐标并写入文件
    with open(os.path.join(labels_path, label), 'w') as f:
        for item in data:
            center_x, center_y, width, height = convert(item, img_width, img_height)
            seq = (str(0), center_x, center_y, width, height)
            sep = ' '
            f.write(sep.join(seq) + '\n')
    f.close()
    print(label.split('.txt')[0]+'.png Finished ! !')
